<template>
  <div ref="chartDom" style="width: 31vw; height: 26vh"></div>
</template>

<script>
export default {
  name: "major",
  data() {
    return {
      chartInstance: null,
    };
  },
  mounted() {
    this.initChart();
  },
  methods: {
    initChart() {
      this.chartInstance = this.$echarts.init(this.$refs.chartDom);

      const categories = [
        "其他服务业",
        "采矿业",
        "教育",
        "技术服务业",
        "金融业",
        "建筑业",
        "供应业",
        "信息技术服务业",
        "制造业",
      ];
      const data = [2.05, 3.43, 3.77, 4.22, 4.89, 9.18, 14.55, 15.26, 35.41];
      const colors = [
        "#ff6b6b",
        "#f7b267",
        "#70c1b3",
        "#6a8caf",
        "#4ecdc4",
        "#c06c84",
        "#9b5de5",
      ];

      const option = {
        backgroundColor: "#0b1f42",
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          textStyle: {
            color: "#ccc",
          },
        },
        grid: {
          top: "2%",
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
          axisLine: { lineStyle: { color: "#fff" } },
          splitLine: { show: false },
          axisLabel: { color: "#fff", fontSize: 10 },
        },
        yAxis: {
          type: "category",
          data: categories,
          axisLine: { lineStyle: { color: "#fff" } },
          axisLabel: { color: "#fff", fontSize: 10 },
        },
        series: [
          {
            name: "数量",
            type: "bar",
            barWidth: "60%", // 尽量占满格子
            barCategoryGap: "30%", // 控制分类间距
            label: {
              show: true,
              position: "right",
              color: "#ffffff",
              fontSize: 10,
              formatter: "{c}%",
            },
            data: data.map((value, index) => ({
              value,
              itemStyle: {
                color: colors[index % colors.length],
                borderRadius: [0, 10, 10, 0], // 顶部圆角
              },
            })),
          },
        ],
      };

      this.chartInstance.setOption(option);
      window.addEventListener("resize", this.handleResize);
    },
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  },
};
</script>

<style scoped>
/* 样式由 ECharts 控制 */
</style>